from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from django.http import HttpResponse
from rest_framework import mixins
from exam.models import Exam, Question, QuestionAnswer
from exam.serializers import ExamSerializer, QuestionSerializer, QuestionAnswerSerializer
from django.utils.decorators import method_decorator
from libs.utils.decorator import request_log
from django.core.exceptions import ObjectDoesNotExist
from libs.utils.response import OBJECT_NOT_FOUND, API_SUCCESS
from rest_framework.decorators import api_view
import logging

class ExamView(ModelViewSet):
    queryset = Exam.objects.all()
    serializer_class = ExamSerializer

    # 使用filter过滤
    my_filter_fields = ('question', 'type')

    ## 获取筛选参数
    def get_kwargs_for_filtering(self):
        filtering_kwargs = {}
        for field in self.my_filter_fields:
            field_value = self.request.query_params.get(field)
            if field_value:
                if field == 'question':
                    filtering_kwargs["question__contains"] = field_value
                else:
                    filtering_kwargs[field] = field_value
        return filtering_kwargs

    def list(self, request):
        """
        商品列表
        """
        filtering_kwargs = self.get_kwargs_for_filtering()

        if filtering_kwargs:
            self.queryset = self.queryset.filter(**filtering_kwargs)

        pagination_queryset = self.paginate_queryset(self.queryset)
        serializer = self.get_serializer(pagination_queryset, many=True)
        resp = self.get_paginated_response(serializer.data)

        return resp

class QuestionView(ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

    # 使用filter过滤
    my_filter_fields = ('question', 'type')

    ## 获取筛选参数
    def get_kwargs_for_filtering(self):
        filtering_kwargs = {}
        for field in self.my_filter_fields:
            field_value = self.request.query_params.get(field)
            if field_value:
                if field == 'question':
                    filtering_kwargs["question__contains"] = field_value
                else:
                    filtering_kwargs[field] = field_value
        return filtering_kwargs

    def list(self, request):
        """
        商品列表
        """
        filtering_kwargs = self.get_kwargs_for_filtering()

        if filtering_kwargs:
            self.queryset = self.queryset.filter(**filtering_kwargs)

        pagination_queryset = self.paginate_queryset(self.queryset)
        serializer = self.get_serializer(pagination_queryset, many=True)
        resp = self.get_paginated_response(serializer.data)

        return resp


